package com.sxhuayuan.parking.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** 签名校验工具类 */
public class SignatureUtils {

	static Logger log = LoggerFactory.getLogger(SignatureUtils.class);

	public static Boolean checkHuabeiPaySign(Map<String, Object> publicData, String secretKey) {
		String sign_ = publicData.get("sign").toString();
		publicData.remove("sign");
		Set<String> keySet = publicData.keySet();
		String[] strings = keySet.toArray(new String[keySet.size()]);
		for (int i = 0; i < strings.length; i++) {
			strings[i] = String.format("%s=%s&", strings[i], publicData.get(strings[i]));
		}
		Arrays.sort(strings);
		StringBuilder builder = new StringBuilder();
		for (String string : strings) {
			builder.append(string);
		}
		String str = builder.append("key=").append(secretKey).toString();
		// log.debug("原始签名字符串：{}", str);
		String sign = DigestUtils.md5Hex(str);
		// log.debug("计算签名={}", sign);
		return sign.equalsIgnoreCase(sign_);
	}

	/**
	 * md5签名
	 * 
	 * @param map
	 * @param key
	 * @param secret
	 * @return
	 */
	public static String signMd5(Map<String, Object> map, String key, String secret) {
		Map<String, Object> tmap = order(map);
		tmap.remove(key);
		final StringBuilder sb = new StringBuilder();
		for (String k : tmap.keySet()) {
			sb.append(k).append("=").append(tmap.get(k)).append("&");
		}
		String str = null;
		if (key == null)
			str = sb.deleteCharAt(sb.length() - 1).toString();
		else {
			sb.append(key).append("=").append(secret);
			str = sb.toString();
		}
		String md5 = DigestUtils.md5Hex(str);
		// log.debug("原始串：{} ,md5={}", str, md5);
		return md5;
	}

	/**
	 * Map key 排序
	 * 
	 * @param map
	 *            map
	 * @return map
	 */
	public static Map<String, Object> order(Map<String, Object> map) {
		HashMap<String, Object> tempMap = new LinkedHashMap<>();
		List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(map.entrySet());

		Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
			public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
				return (o1.getKey()).toString().compareTo(o2.getKey());
			}
		});

		for (int i = 0; i < infoIds.size(); i++) {
			Map.Entry<String, Object> item = infoIds.get(i);
			tempMap.put(item.getKey(), item.getValue());
		}
		return tempMap;
	}
}
